import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/user'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component: () => import('../views/HomeView.vue'),
      meta: { requiresAuth: true },
    },
    {
      path: '/student-manage',
      name: 'studentManage',
      component: () => import('../views/StudentManage.vue'),
      meta: { requiresAuth: true },
    },
    {
      path: '/user-manager',
      name: 'userManager',
      component: () => import('../views/UserManager.vue'),
      meta: { requiresAuth: true, adminOnly: true },
    },
    {
      path: '/user-center',
      name: 'userCenter',
      component: () => import('../views/UserCenter.vue'),
      meta: { requiresAuth: true },
    },
    {
      path: '/injury-report',
      name: 'injuryReport',
      component: () => import('../views/HealthReport.vue'),
      meta: { requiresAuth: true },
    },
    {
      path: '/online-evaluation',
      name: 'onlineEvaluation',
      component: () => import('../views/OlineEvaluation.vue'),
      meta: { requiresAuth: true },
    },
    {
      path: '/offline-evaluation',
      name: 'offlineEvaluation',
      component: () => import('../views/OfferEvaluation.vue'),
      meta: { requiresAuth: true },
    },
    {
      path: '/feedback',
      name: 'feedback',
      component: () => import('../views/FeedBack.vue'),
      meta: { requiresAuth: true, adminOnly: true },
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('../views/LoginView.vue'),
      meta: { guest: true },
    },
    {
      path: '/register',
      name: 'register',
      component: () => import('../views/RegisterView.vue'),
      meta: { guest: true },
    },
    {
      path: '/:pathMatch(.*)*',
      redirect: '/',
    },
    {
      path: '/create-plan/:reportId',
      name: 'createPlan',
      component: () => import('../views/CreatePlan.vue'),
      meta: { requiresAuth: true },
    },
    {
      path: '/system-management',
      name: 'systemManagement',
      component: () => import('../views/SystemManager.vue'),
      meta: { requiresAuth: true, adminOnly: true },
    },
  ],
})

// 全局前置守卫
router.beforeEach(async (to, from, next) => {
  // 获取用户存储
  const userStore = useUserStore()

  // 允许直接访问登录和注册页面
  if (to.meta.guest) {
    // 如果已登录并尝试访问登录页，重定向到首页
    if (userStore.isLoggedIn && (to.name === 'login' || to.name === 'register')) {
      next({ name: 'home' })
      return
    }
    next()
    return
  }

  // 检查用户是否已登录
  const userId = localStorage.getItem('userId')
  const userRole = localStorage.getItem('userRole')

  // 如果有基本用户信息但没有登录状态，尝试初始化用户信息
  if (userId && userRole && !userStore.isLoggedIn) {
    try {
      await userStore.init()
    } catch (error) {
      console.error('初始化用户信息失败:', error)
      next({ name: 'login' })
      return
    }
  }

  // 要求登录但未登录，重定向到登录页
  if (to.meta.requiresAuth && !userStore.isLoggedIn) {
    next({ name: 'login' })
    return
  }

  // 检查管理员权限
  if (to.meta.adminOnly) {
    // 只允许管理员和超级管理员访问
    if (
      userStore.role !== '管理员' &&
      userStore.role !== '超级管理员' &&
      userStore.role !== '教师'
    ) {
      next({ name: 'home' }) // 无权限则导向首页
      return
    }
  }

  // 默认放行
  next()
})

export default router
